package com.diorsunion.hedge.bo.message;


import com.diorsunion.hedge.io.Message;
import com.diorsunion.hedge.io.MessageBO;
import com.diorsunion.hedge.io.MessageHandler;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * Created by wangnima on 2016/5/29.
 */
@Component("ServerCmdMessageBO")
public class ServerMessageBO implements MessageBO {

    @Resource @Qualifier("AccountServerHandler")
    MessageHandler accountServerHandler;

    Map<String,List<MessageHandler>> messageHandlerMap = Maps.newHashMap();

    public List<Message>  execute(Message message){
        List<Message> resultList = Lists.newArrayList();
        if(message==null || message.data==null){
            return resultList;
        }
        String className = message.data.getClass().getName();
        List<MessageHandler> messageHandlerSet = messageHandlerMap.get(className);
        if(!CollectionUtils.isEmpty(messageHandlerSet)){
            messageHandlerSet.parallelStream().forEach(x->messageHandlerexecute(x, message, resultList));
        }
        return resultList;
    }

    public void messageHandlerexecute(final MessageHandler messageHandler,final Message message,final List<Message> messageList){
        Function<Serializable,Message> function = messageHandler.getFunction(message.name);
        if(function==null){
            return;
        }
        Message resultMessage = function.apply(message.data);
        if(resultMessage!=null){
            messageList.add(resultMessage);
        }
    }

    @PostConstruct
    public void init(){
        initHandler(accountServerHandler);
    }

    @Override
    public Map<String, List<MessageHandler>> getMessageHandlerMap() {
        return messageHandlerMap;
    }
}
